<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/component/pear/css/pear.css" />
    <script src="/static/component/layui/layui.js"></script>
    <script src="/static/component/pear/pear.js"></script>
</head>
<body>
<form class="layui-form" action="">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
                <label class="layui-form-label">
                    区服
                </label>
                <div class="layui-input-block">
                    <select name="serverid" id="serverid" lay-search>
                        <option value="">服务器ID(可输入后选择)</option>
                        {volist name="ServerLs" id="server"}
                        <option value="{$server.sid}">{$server.name}</option>
                        {/volist}
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">
                    玩家账号
                </label>
                <div class="layui-input-block">
                    <input type="text" class="layui-input layui-form-danger" name="player" id="player" type="text" value="{$model['player']??""}"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">
                    角色名称
                </label>
                <div class="layui-input-block">
                    <select name="actorid" id="actorid" lay-search>
                        <option value=""></option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">
                    物品预设
                </label>
                <div class="layui-input-block">
                    <textarea name="goodsid" id="goodsid"  lay-verify="goodsid" placeholder="不需要填写！！！点击按钮进行添加！" class="layui-textarea" readonly>
                        {$model['goodsid']??""}
                    </textarea>
                </div>
            </div>

            <div class="layui-form-item" >
                <div class="layui-input-block" id='listbox' style="border: 1px dashed #fffb00;">
                    
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">
                </label>
                <div class="layui-input-inline">
                    <select name="goodsls" id="goodsls" lay-search>
                        <option value="">选择预设好的物品</option>
                        {volist name="Goodsls" id="Goodsls"}
                        <option value="{$Goodsls.id}">{$Goodsls.sendname}</option>
                        {/volist}
                    </select>
                </div>
                <!-- <div class="layui-input-inline">
                    <input type="text" class="layui-input layui-form-danger" name="goodsnum" id="goodsnum" type="text" />
                </div> -->
                <div class="layui-input-inline">
                    <button type="button" class="layui-btn layui-btn-normal" id="btnAddgoods" >添加</button>
                </div>
            </div>

        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm" lay-submit="" lay-filter="save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>
<script>
    layui.use(['form', 'jquery', 'layedit', 'uploads'], function () {
        let form = layui.form;
        let $ = layui.jquery;
        let layedit = layui.layedit
        layedit.set({
            uploadImage: {
                url: "{$Request.root}/index/upload"
            }
        });
        //建立编辑器
        
        form.on('submit(save)', function (data) {
            
            $.ajax({
                data: JSON.stringify(data.field),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (res) {
                    //判断有没有权限
                    if (res && res.code == 999) {
                        layer.msg(res.msg, {
                            icon: 5,
                            time: 2000,
                        })
                        return false;
                    } else if (res.code == 200) {
                        layer.msg(res.msg,{icon:1,time:1000}, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭当前页
                            parent.layui.table.reload("dataTable");
                        });
                    } else {
                        layer.msg(res.msg,{icon:2,time:1000});
                    }
                }
            })
            return false;
        });

        $("#player").on("input", function (e) {
            //获取input输入的值
            var value = e.delegateTarget.value;
            if (value != null && value != '') {
                getActors();
            }
        })
        var itemList = {}

        loadValue();

        function loadValue(){
            var serverid="{$model['serverid']}";
            $('#serverid').val(serverid);
            getActors();
            
            var da="{$model['goodsid']}";
            // da = da.replace(/&quot;/g, '"'); // 替换所有的 &quot; 为 "
            // var decodedData = JSON.parse(da);
            // itemList=decodedData;

            // for (var key in decodedData) {
            //     if (decodedData.hasOwnProperty(key)) {
            //         appendChildtoHtml(key,decodedData[key].stat,decodedData[key].name);
            //     }
            // }
            var result = da.split(';');

            result.forEach(function(substring) {
                var da1=substring.split(',');
                appendChildtoHtml(da1[0],da1[2],da1[1]);
            });





            form.render();
        }

        function getActors() {
            var player = $('#player').val();
            var serverid = $("select[name='serverid']").val();
            if (serverid.trim() === "") {
                layer.msg("请先填写区服名称！！！");
                return
            }
            if (player.trim() === "") {
                layer.msg("请先填写账号！！！");
                return
            }
            
            $.post('queryuname', { actorname: player, serverid: serverid }, function (res) {
                //判断有没有权限
                if (res && res.code == 999) {
                    layer.msg(res.msg, {
                        icon: 5,
                        time: 2000,
                    })
                    return false;
                } else if (res.code == 200) {
                    // 清空下拉框中的所有选项
                    $("#actorid").empty();
                        // 遍历data数组并添加选项
                        res.data.forEach(function (item) {
                            $("#actorid").append(
                                '<option value="' + item.actorid +'">' + item.actorname + '</option>'
                            );
                        });
                        // 使用layui的下拉框模块进行渲染
                        // layui.form.render('select');
                        form.render();
                    
                } else {
                    layer.msg(res.msg)
                    console.log(res.msg)
                }
                form.render();
            })
        }

        

        $('#btnAddgoods').click(function () {
            var itemid = $('#goodsls').val().trim();
            var itemnum = "1";
            var itemName = $('#goodsls').find("option:selected").text().trim();
            if (itemid == '') {
                layer.msg('请选择物品。。');
                return false;
            }
            appendChildtoHtml(itemid,itemnum,itemName);
        });



        function appendChildtoHtml(itemid,itemnum,itemName){
            // 创建一个新按钮元素
            var newButton = document.createElement('button');
            newButton.setAttribute('type', 'button');
            newButton.setAttribute('class', 'layui-btn layui-btn-primary layui-border-black');
            newButton.innerText = itemName + '=>' + itemnum;
            // 向itemList对象插入数据
            itemList[itemid] = {name: itemName, stat: parseInt(itemnum)};
            
            if (itemList == {} || itemList === undefined) {
                $('#goodsid').val('')
            }else{
                var goodsStr='';
                for (var key in itemList) {
                    if (itemList.hasOwnProperty(key)) {
                        goodsStr+=key+','+itemList[key].name+','+itemList[key].stat+';'
                    }
                }
                // $('#goodsid').val(JSON.stringify(itemList)) 
                $('#goodsid').val(goodsStr.substring(0, goodsStr.length - 1)) 
            }
            
            // 添加点击事件，用于删除按钮自身
            newButton.addEventListener('click', function () {
                // 从itemList中删除对应数据
                delete itemList[itemid];
                
                var buttons = document.getElementsByClassName('layui-btn');
                for (var i = 0; i < buttons.length; i++) {
                    var buttonText = buttons[i].innerText;
                    if (buttonText.includes(itemName) && buttonText.includes(itemnum)) {
                        buttons[i].parentNode.removeChild(buttons[i]);
                        i--; // 因为删除了一个按钮，需要将索引减一
                    }
                }

                if (itemList == {} || itemList === undefined) {
                    $('#goodsid').val('')
                }else{
                    var goodsStr='';
                for (var key in itemList) {
                    if (itemList.hasOwnProperty(key)) {
                        goodsStr+=key+','+itemList[key].name+','+itemList[key].stat+';'
                    }
                }
                // $('#goodsid').val(JSON.stringify(itemList)) 
                $('#goodsid').val(goodsStr.substring(0, goodsStr.length - 1)) 
                }
            });

            // 将新按钮添加到listbox中
            var myDiv = document.getElementById("listbox");
            myDiv.appendChild(newButton);
            
        }


    })
</script>
</body>
</html>